﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Ldt.DataEngine.DataFlowParse.Model;
using LdtDataEngin.ModuleDetail.BaseModule.Optimization;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommHelp;
using LdtJudge.DataEngine.Common.DataSave;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.Data.DataParseStorage;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.DataModel.DataParseStorage;
using LdtJudge.DataEngine.Model.ElmentModel;
using LdtJudge.DataEngine.Model.XMLConfigModel.DataStores;
using Newtonsoft.Json;

namespace LdtDataEngin.ModuleDetail.CaseCauseElementOpt
{
    public class CaseCauseOptimization : OptimizationBase
    {
        private List<An_anjiancunchu> optimizationResultList;

        private List<DOCLocationModel> locationModelList;
        public CaseCauseOptimization(DataContext context,string moduleName)
        {
            dataContext = context;
            this.ModuleName = moduleName;
            DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
            optimizationResultList = anjiancunchudal.GetList(dataContext.DataLayerOpt.CaseId);
            
        }

        //public void Optimization1()
        //{
        //    Stopwatch stopwatch = new Stopwatch();
        //    SetModuleProcess(ModuleName, 0,dataContext.InteractiveShow.inputParameterModel);
        //    stopwatch.Start();
        //    DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
        //    //分析数据结果
        //    List<DataModel> dataModelAsisList = dataContext.DataLayerAns.ElementAnalsisDataModelResults;
        //    //上次优选结果数据
        //    List<DataModel> dataModelsOPList = new List<DataModel>();
        //    var configModel = dataContext.DataLayerSys.GetConfigModel(ModuleName);

        //    if (configModel.ConfigDetail.Any())
        //    {

        //        string causeLocalContent = string.Empty;
        //        string causeStageContent = string.Empty;
        //        ConfigModel causeLocalConfig = configModel.ConfigDetail.FirstOrDefault(x => x.ExecuteCode == "elementpath.xml");
        //        if (causeLocalConfig != null)
        //            causeLocalContent = causeLocalConfig.ConfigContent;
        //        ConfigModel causeStageConfig = configModel.ConfigDetail.FirstOrDefault(x => x.Code.ToLower() == "causestagelocation");
        //        if (causeStageConfig != null)
        //            causeStageContent = causeStageConfig.ConfigContent;
        //        locationModelList = GetLocationModels(causeLocalContent, causeStageContent);
        //        dataContext.DataLayerSys.locationModelList = locationModelList;
        //    }
            
        //    if (dataContext.DataLayerOpt.SourdatModleList!=null && dataContext.DataLayerOpt.SourdatModleList.Count>0)
        //    {
        //        CaseCauseElementOptimization(dataContext.DataLayerOpt.SourdatModleList, dataModelAsisList);
        //    }
        //    else
        //    {
        //        dataContext.InteractiveShow.LogShow("案件信息无优选结果，无法优选案由信息");
        //    }
        //    FormatDataSource formatDataSource = new FormatDataSource(dataContext);
        //    formatDataSource.FromatNodeList(dataModelsOPList);
        //    CaseCauseElementOptimization(dataModelsOPList,dataModelAsisList);
        //    stopwatch.Stop();
        //    SetModuleProcess(ModuleName + "_" + stopwatch.Elapsed.TotalMilliseconds.ToString("0"), 100,dataContext.InteractiveShow.inputParameterModel);
        //}
        public void Optimization()
        {
            Stopwatch stopwatch = new Stopwatch();
            SetModuleProcess(ModuleName, 0, dataContext.InteractiveShow.inputParameterModel);
            stopwatch.Start();
            DAL_An_anjiancunchu anjiancunchudal = new DAL_An_anjiancunchu();
            //分析数据结果
            //上次优选结果数据
            List<DataModel> dataModelsOPList = new List<DataModel>();
            var configModel = dataContext.DataLayerSys.GetConfigModel(ModuleName);

            if (configModel.ConfigDetail.Any())
            {

                string causeLocalContent = string.Empty;
                string causeStageContent = string.Empty;
                ConfigModel causeLocalConfig = configModel.ConfigDetail.FirstOrDefault(x => x.ExecuteCode == "elementpath.xml");
                if (causeLocalConfig != null)
                    causeLocalContent = causeLocalConfig.ConfigContent;
                ConfigModel causeStageConfig = configModel.ConfigDetail.FirstOrDefault(x => x.Code.ToLower() == "causestagelocation");
                if (causeStageConfig != null)
                    causeStageContent = causeStageConfig.ConfigContent;
                locationModelList = GetLocationModels(causeLocalContent, causeStageContent);
                dataContext.DataLayerSys.locationModelList = locationModelList;
            }

            if (dataContext.DataLayerOpt.SourdatModleList != null && dataContext.DataLayerOpt.SourdatModleList.Count > 0)
            {
                ElementOptimization(dataContext.DataLayerAns.ElementAnalsisDataModelResults);
            }
            else
            {
                dataContext.InteractiveShow.LogShow("案件信息无优选结果，无法优选案由信息");
            }
            FormatDataSource formatDataSource = new FormatDataSource(dataContext);
            formatDataSource.FromatNodeList(dataModelsOPList);
            ElementOptimization(dataContext.DataLayerAns.ElementAnalsisDataModelResults);
            stopwatch.Stop();
            SetModuleProcess(ModuleName + "_" + stopwatch.Elapsed.TotalMilliseconds.ToString("0"), 100, dataContext.InteractiveShow.inputParameterModel);
        }

        public void ElementOptimization(Dictionary<string,List<DataModel>> dataModelAsList) 
        {
            Dictionary<string, List<DataModel>> dicOpElementList = new Dictionary<string, List<DataModel>>();
            if (dataModelAsList==null || dataModelAsList.Count==0)
            {
                #region 当前无本次案由优选结果
                //当前无本次优选能结果案由。
                if (optimizationResultList.FirstOrDefault(a => a.Cunchuleixing == "2") != null)
                {
                    foreach (var resultModel in optimizationResultList)
                    {
                        DataSoursModel dataSoursModelOP = GetDataSoursModel(ReadDataXML(resultModel.Wenjianid));
                        string casecauseid = resultModel.Anyouid;
                        dicOpElementList.Add(casecauseid, dataSoursModelOP.dataModelList);
                    }
                }
                #endregion
            }
            else
            {
                #region 存在本次案由优选结果
                foreach (var dataasislist in dataModelAsList)
                {
                    string casecauseid = dataasislist.Key;
                    if (optimizationResultList.FirstOrDefault(a => a.Cunchuleixing == "2") != null)
                    {
                        //查询是否有符合案由类型的要素
                        An_anjiancunchu an_Anjiancunchu = optimizationResultList.FirstOrDefault(a => a.Anyouid == casecauseid);
                        if (an_Anjiancunchu != null)
                        {
                            //案由要素优选
                            List<DataModel> ReturndataModelList = new List<DataModel>();
                            DataSoursModel dataSoursModelOP = GetDataSoursModel(ReadDataXML(an_Anjiancunchu.Wenjianid));
                            if (dataSoursModelOP != null && dataSoursModelOP.dataModelList.Count > 0)
                            {
                                List<DataModel> dataModelsAissNodeList = dataasislist.Value.Where(a => a.XmlPath.IndexOf("主张方") > -1).ToList();
                                List<DataModel> dataModelsOPPersonnelList = dataSoursModelOP.dataModelList.Where(a => a.XmlPath.IndexOf("主张方") > -1).ToList();
                                dataModelsOPPersonnelList = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelsOPPersonnelList));
                                foreach (DataModel itemAdvocate in dataModelsAissNodeList)
                                {
                                    DataModel dataModelasisPrentNode = dataasislist.Value.FirstOrDefault(a => a.ID == itemAdvocate.ParentId);
                                    if (dataModelasisPrentNode.ParentId == dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID)
                                    {
                                        AttributeInfo itemNameDataModel = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名或名称");
                                        AttributeInfo itemSuitidDataModel = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名或名称");

                                        if (itemNameDataModel != null && itemSuitidDataModel != null)
                                        {
                                            string name = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名或名称").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                            string suitid = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方诉讼地位").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                            //获取结果要素对应节点信息
                                            DataModel petitionDatamodel = new DataModel();
                                            try
                                            {
                                                petitionDatamodel = dataSoursModelOP.dataModelList.FirstOrDefault(a => a.XmlPath == dataModelasisPrentNode.XmlPath + "/主张方" && a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名或名称").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == name
                                                 && a.AttributesList.FirstOrDefault(g => g.Name == "主张方诉讼地位").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == suitid);
                                                if (petitionDatamodel != null)
                                                {
                                                    dataModelsOPPersonnelList.Remove(petitionDatamodel);
                                                }
                                                petitionDatamodel = dataSoursModelOP.dataModelList.FirstOrDefault(a => a.ID == petitionDatamodel.ParentId);
                                            }
                                            catch (Exception)
                                            {
                                                dataContext.InteractiveShow.LogShow("根据主张方查询案由要素错误，人员姓名" + name + "诉讼地位：" + suitid);
                                            }
                                            List<DataModel> dataModelCuases = new List<DataModel>();
                                            string elementid = "";
                                            if (itemAdvocate.XmlPath.IndexOf("诉请要素") > -1)
                                            {
                                                elementid = "1";
                                                if (petitionDatamodel != null)
                                                {
                                                    dataModelCuases = SubordinateDataModelList(dataSoursModelOP.dataModelList, petitionDatamodel);
                                                }
                                                else
                                                {
                                                    dataModelCuases = SubordinateDataModelList(dataasislist.Value, dataModelasisPrentNode);
                                                }

                                            }
                                            else if (itemAdvocate.XmlPath.IndexOf("事实要素") > -1)
                                            {
                                                elementid = "2";
                                                if (petitionDatamodel != null && petitionDatamodel.ID != null)
                                                {
                                                    dataModelCuases = SubordinateDataModelList(dataSoursModelOP.dataModelList, petitionDatamodel);
                                                }
                                                else
                                                {
                                                    dataModelCuases = SubordinateDataModelList(dataasislist.Value, dataModelasisPrentNode);
                                                }
                                            }
                                            if (OptimizeElement.CaseTypeList.FirstOrDefault(a => a.Code == suitid) != null)
                                            {
                                                List<Xmllable> xmllableList = OptimizeElement.CaseTypeList.FirstOrDefault(a => a.Code == suitid).XmlFactTypeList.FirstOrDefault(a => a.Type == elementid).XmllableList;
                                                string xmltype = "";
                                                string xmlpriority = "";
                                                foreach (Xmllable xmllable in xmllableList)
                                                {
                                                    if (string.IsNullOrEmpty(xmllable.Type))
                                                    {
                                                        xmllable.Type = xmltype;
                                                    }
                                                    else
                                                    {
                                                        xmltype = xmllable.Type;
                                                    }
                                                    if (string.IsNullOrEmpty(xmllable.Priority))
                                                    {
                                                        xmllable.Priority = xmlpriority;
                                                    }
                                                    else
                                                    {
                                                        xmlpriority = xmllable.Priority;
                                                    }
                                                }
                                                //分析结果数据
                                                List<DataModel> dataModelsAsisList = SubordinateDataModelList(dataasislist.Value, dataModelasisPrentNode);
                                                dataModelsAsisList = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelsAsisList));

                                                CasecaseuseElmentOptimization(dataModelsAsisList, dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID, dataModelCuases, xmllableList);
                                                if (ReturndataModelList.Count == 0)
                                                {
                                                    if (dataModelCuases != null)
                                                    {
                                                        ReturndataModelList.AddRange(dataModelCuases);
                                                    }
                                                }
                                                else
                                                {
                                                    foreach (DataModel dataModel in dataModelCuases.Where(a => a.ParentId == dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID || a.ParentId == null || a.ParentId == ""))
                                                    {
                                                        if (ReturndataModelList.FirstOrDefault(a => a.ID == dataModel.ID) == null)
                                                        {
                                                            ReturndataModelList.AddRange(SubordinateDataModelList(dataModelCuases, dataModel));

                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                foreach (DataModel personnelModel in dataModelsOPPersonnelList)
                                {
                                    DataModel dataModelRoot = dataSoursModelOP.dataModelList.FirstOrDefault(a => a.ID == personnelModel.ParentId);
                                    List<DataModel> dataModelValueList = SubordinateDataModelList(dataSoursModelOP.dataModelList, dataModelRoot);
                                    ReturndataModelList.AddRange(dataModelValueList);
                                }
                                ReturndataModelList = ReturndataModelList.Distinct().ToList();
                                dicOpElementList.Add(casecauseid, ReturndataModelList);
                            }
                        }
                        else
                        {
                            //该案由没有优选结果
                            dicOpElementList.Add(dataasislist.Key, dataasislist.Value);
                        }

                    }
                    else
                    {
                        //分析结果即是优选结果
                        dicOpElementList.Add(dataasislist.Key, dataasislist.Value);
                    }
                }
                #endregion
            }
           
            if (dicOpElementList.Count>0)
            {
                CaseElementListByCauseElmentList(dataContext.DataLayerOpt.SourdatModleList, dicOpElementList);
            }
            else
            {
                dataContext.InteractiveShow.LogShow("本次无案由优选结果！");
            }

        }

        ///// <summary>
        ///// 案由要素优选
        ///// </summary>
        ///// <param name="dataModelOpList">案件要素分析结果</param>
        ///// <param name="dataModelAsList">案由要素分析结果</param>
        //public void CaseCauseElementOptimization(List<DataModel> dataModelOpList, List<DataModel> dataModelAsList)
        //{

        //    if (optimizationResultList.FirstOrDefault(a => a.Cunchuleixing == "2") != null)
        //    {
        //        #region 案由要素优选--存在上次优选结果
        //        //案由要素优选
        //        List<DataModel> ReturndataModelList = new List<DataModel>();

        //        DataSoursModel dataSoursModelOP = GetDataSoursModel(ReadDataXML(optimizationResultList.FirstOrDefault(a => a.Cunchuleixing == "2").Wenjianid));
        //        if (dataContext.DataLayerAns.ElementAnalsisDataModelResults != null && dataSoursModelOP != null && dataSoursModelOP.dataModelList.Count > 0)
        //        {
        //            List<DataModel> dataModelsAissNodeList = dataContext.DataLayerAns.ElementAnalsisDataModelResults.Where(a => a.XmlPath.IndexOf("主张方") > -1).ToList();
        //            List<DataModel> dataModelsOPPersonnelList = dataSoursModelOP.dataModelList.Where(a => a.XmlPath.IndexOf("主张方") > -1).ToList();
        //            dataModelsOPPersonnelList = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelsOPPersonnelList));
        //            foreach (DataModel itemAdvocate in dataModelsAissNodeList)
        //            {
        //                DataModel dataModelasisPrentNode = dataContext.DataLayerAns.ElementAnalsisDataModelResults.FirstOrDefault(a => a.ID == itemAdvocate.ParentId);
        //                if (dataModelasisPrentNode.ParentId == dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID)
        //                {
        //                    AttributeInfo itemNameDataModel = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名或名称");
        //                    AttributeInfo itemSuitidDataModel = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名或名称");

        //                    if (itemNameDataModel != null && itemSuitidDataModel != null)
        //                    {
        //                        string name = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方姓名或名称").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
        //                        string suitid = itemAdvocate.AttributesList.FirstOrDefault(a => a.Name == "主张方诉讼地位").sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
        //                        //获取结果要素对应节点信息
        //                        DataModel petitionDatamodel = new DataModel();
        //                        try
        //                        {
        //                            petitionDatamodel = dataSoursModelOP.dataModelList.FirstOrDefault(a => a.XmlPath == dataModelasisPrentNode.XmlPath + "/主张方" && a.AttributesList.FirstOrDefault(b => b.Name == "主张方姓名或名称").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == name
        //                             && a.AttributesList.FirstOrDefault(g => g.Name == "主张方诉讼地位").sourceList.FirstOrDefault(c => c.IsCheck == "1").SaveValue == suitid);
        //                            if (petitionDatamodel != null)
        //                            {
        //                                dataModelsOPPersonnelList.Remove(petitionDatamodel);
        //                            }
        //                            petitionDatamodel = dataSoursModelOP.dataModelList.FirstOrDefault(a => a.ID == petitionDatamodel.ParentId);
        //                        }
        //                        catch (Exception)
        //                        {
        //                            dataContext.InteractiveShow.LogShow("根据主张方查询案由要素错误，人员姓名" + name + "诉讼地位：" + suitid);
        //                        }
        //                        List<DataModel> dataModelCuases = new List<DataModel>();
        //                        string elementid = "";
        //                        if (itemAdvocate.XmlPath.IndexOf("诉请要素") > -1)
        //                        {
        //                            elementid = "1";
        //                            if (petitionDatamodel != null)
        //                            {
        //                                dataModelCuases = SubordinateDataModelList(dataSoursModelOP.dataModelList, petitionDatamodel);
        //                            }
        //                            else
        //                            {
        //                                dataModelCuases = SubordinateDataModelList(dataContext.DataLayerAns.ElementAnalsisDataModelResults, dataModelasisPrentNode);
        //                            }

        //                        }
        //                        else if (itemAdvocate.XmlPath.IndexOf("事实要素") > -1)
        //                        {
        //                            elementid = "2";
        //                            if (petitionDatamodel != null && petitionDatamodel.ID != null)
        //                            {
        //                                dataModelCuases = SubordinateDataModelList(dataSoursModelOP.dataModelList, petitionDatamodel);
        //                            }
        //                            else
        //                            {
        //                                dataModelCuases = SubordinateDataModelList(dataContext.DataLayerAns.ElementAnalsisDataModelResults, dataModelasisPrentNode);
        //                            }
        //                        }
        //                        if (OptimizeElement.CaseTypeList.FirstOrDefault(a => a.Code == suitid) != null)
        //                        {
        //                            List<Xmllable> xmllableList = OptimizeElement.CaseTypeList.FirstOrDefault(a => a.Code == suitid).XmlFactTypeList.FirstOrDefault(a => a.Type == elementid).XmllableList;
        //                            string xmltype = "";
        //                            string xmlpriority = "";
        //                            foreach (Xmllable xmllable in xmllableList)
        //                            {
        //                                if (string.IsNullOrEmpty(xmllable.Type))
        //                                {
        //                                    xmllable.Type = xmltype;
        //                                }
        //                                else
        //                                {
        //                                    xmltype = xmllable.Type;
        //                                }
        //                                if (string.IsNullOrEmpty(xmllable.Priority))
        //                                {
        //                                    xmllable.Priority = xmlpriority;
        //                                }
        //                                else
        //                                {
        //                                    xmlpriority = xmllable.Priority;
        //                                }
        //                            }
        //                            //分析结果数据
        //                            List<DataModel> dataModelsAsisList = SubordinateDataModelList(dataContext.DataLayerAns.ElementAnalsisDataModelResults, dataModelasisPrentNode);
        //                            dataModelsAsisList = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelsAsisList));

        //                            CasecaseuseElmentOptimization(dataModelsAsisList, dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID, dataModelCuases, xmllableList);
        //                            if (ReturndataModelList.Count == 0)
        //                            {
        //                                if (dataModelCuases != null)
        //                                {
        //                                    ReturndataModelList.AddRange(dataModelCuases);
        //                                }
        //                            }
        //                            else
        //                            {
        //                                foreach (DataModel dataModel in dataModelCuases.Where(a => a.ParentId == dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID || a.ParentId == null || a.ParentId == ""))
        //                                {
        //                                    if (ReturndataModelList.FirstOrDefault(a => a.ID == dataModel.ID) == null)
        //                                    {
        //                                        ReturndataModelList.AddRange(SubordinateDataModelList(dataModelCuases, dataModel));

        //                                    }
        //                                }
        //                            }

        //                        }
        //                    }
        //                }
        //            }
        //            foreach (DataModel personnelModel in dataModelsOPPersonnelList)
        //            {
        //                DataModel dataModelRoot = dataSoursModelOP.dataModelList.FirstOrDefault(a => a.ID == personnelModel.ParentId);
        //                List<DataModel> dataModelValueList = SubordinateDataModelList(dataSoursModelOP.dataModelList, dataModelRoot);
        //                ReturndataModelList.AddRange(dataModelValueList);
        //            }
        //            ReturndataModelList = ReturndataModelList.Distinct().ToList();
        //            foreach (DataModel dataModel1Value in dataModelOpList.Where(a => a.ID == a.ParentId))
        //            {
        //                dataModel1Value.ParentId = "";
        //            }
        //            CaseElementListByCauseElmentList(dataModelOpList, ReturndataModelList);
        //        }
        //        #endregion
        //    }
        //    else
        //    {
        //        #region 案由要素优选--不存在上次优选结果
        //        if (dataContext.DataLayerAns.ElementAnalsisDataModelResults != null)
        //        {
        //            CaseElementListByCauseElmentList(dataModelOpList, dataContext.DataLayerAns.ElementAnalsisDataModelResults);
        //        }
        //        #endregion
        //    }

        //}

        /// <summary>
        /// 将案由要素优选结果嵌入案件要素优选结果
        /// </summary>
        /// <param name="caseElmentdataModelList">案件要素优选结果</param>
        /// <param name="diccauseElementdataModelList">案由要素优选结果</param>
        public void CaseElementListByCauseElmentList(List<DataModel> caseElmentdataModelList, Dictionary<string,List<DataModel>> diccauseElementdataModelList) 
        {
            var locationModel = locationModelList.FirstOrDefault(a => a.DocType.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
            if (locationModel != null && diccauseElementdataModelList != null && diccauseElementdataModelList.Count > 0 && caseElmentdataModelList.Count > 0)
            {
                string path = locationModel.EelementPaht;
                DataModel dataModelCause = caseElmentdataModelList.FirstOrDefault(a => a.XmlPath == path);
                if (dataModelCause == null)
                {
                    CaseNodeUpdate(caseElmentdataModelList, path);
                    dataModelCause = caseElmentdataModelList.FirstOrDefault(a => a.XmlPath == path);
                }
                if (dataModelCause != null)
                {
                    DelectNodeByDataModel(dataModelCause.ID, caseElmentdataModelList);
                }
                DataModel dataRomve = caseElmentdataModelList.FirstOrDefault(a => a.XmlPath == path + "/案由要素");
                //删除节点
                if (dataRomve != null)
                {
                    List<DataModel> dataRomList = caseElmentdataModelList.Where(a => a.XmlPath == path + "/案由要素").ToList();
                    foreach (DataModel modeRomve in dataRomList)
                    {
                        caseElmentdataModelList.Remove(modeRomve);
                    }
                }
                foreach (var diccauseMode in diccauseElementdataModelList)
                {
                    string casecauseid = diccauseMode.Key;
                    List<DataModel> causeElementdataModelList = diccauseMode.Value;
                    RestructureElment(causeElementdataModelList, casecauseid, casecauseid);

                    DataModel dataModelCauseName = new DataModel();
                    dataModelCauseName.ID = Snowflake.Instance().GetId().ToString();
                    dataModelCauseName.XmlPath = path + "/案由要素";
                    dataModelCauseName.sourceData = new SourceData();
                    dataModelCauseName.CauseType = "1";
                    dataModelCauseName.ParentId = dataModelCause?.ID;
                    dataModelCauseName.sourceData.sourceList = new List<Source>();
                    Source source = new Source();
                    source.SourceCode = dataContext.DataLayerAns.SourceCode;
                    source.IsCheck = "1";
                    dataModelCauseName.sourceData.sourceList.Add(source);
                    caseElmentdataModelList.Add(dataModelCauseName);
                    //保存案由要素优选结果
                    dataContext.DataLayerOpt.ElementOptimizationResults = diccauseElementdataModelList;
                    List<DataModel> dataModelCauseModleList = causeElementdataModelList.Where(a => a.ParentId == casecauseid).ToList();
                    //案由要素优选结果
                    DataSoursModel causeDataSoursModel = new DataSoursModel();
                    causeDataSoursModel.dataModelList = new List<DataModel>();

                    foreach (DataModel causeModel in dataModelCauseModleList)
                    {
                        if (causeElementdataModelList.FirstOrDefault(a => a.ParentId == causeModel.ID && a.XmlPath.IndexOf("主张方") > -1) != null)
                        {
                            List<DataModel> dataModelElment = SubordinateDataModelList(causeElementdataModelList, causeModel);
                            string datamodeljson = JsonConvert.SerializeObject(dataModelElment);
                            dataModelElment = JsonConvert.DeserializeObject<List<DataModel>>(datamodeljson);
                            DataModelIDByReset(dataModelElment, "", "");
                            string jsondata = JsonConvert.SerializeObject(dataModelElment);
                            causeDataSoursModel.dataModelList.AddRange(JsonConvert.DeserializeObject<List<DataModel>>(jsondata));
                            causeModel.ParentId = dataModelCauseName.ID;
                            dataModelElment.FirstOrDefault(a => a.ParentId == casecauseid).ParentId = dataModelCauseName.ID;
                            caseElmentdataModelList.AddRange(dataModelElment);
                        }
                        else
                        {
                            causeModel.ParentId = casecauseid + "_1";
                        }
                    }
                }

                dataContext.DataLayerOpt.OptimizeCauseEntityXml = XmlUtility.SerializeToXml<Dictionary<string, List<DataModel>>>(diccauseElementdataModelList);
                dataContext.DataLayerOpt.SourdatModleList = caseElmentdataModelList;
                //dataContext.DataLayerOpt.OptimizationXml = DataModelByXml(caseElmentdataModelList);
                dataContext.DataLayerOpt.OptimizationXml = XmlUtility.DataModelByXml(caseElmentdataModelList);
            }
        }

        /// <summary>
        /// 案件信息优选
        /// </summary>
        /// <param name="dataModelAsisList"></param>
        /// <param name="prentID"></param>
        /// <param name="dataModelsOPList"></param>
        public void CasecaseuseElmentOptimization(List<DataModel> dataModelAsisList, string prentID, List<DataModel> dataModelsOPList, List<Xmllable> XmllableList)
        {
            List<DataModel> dataModelsAissNodeList = new List<DataModel>();

            dataModelsAissNodeList = dataModelAsisList.Where(a => a.ParentId == prentID).ToList();
            if (dataModelsAissNodeList.Count > 0)
            {
                Xmllable xmllableCofigs = XmllableList.FirstOrDefault(a => a.Xmlpath == dataModelsAissNodeList[0].XmlPath);
                if (xmllableCofigs != null && xmllableCofigs.Type == "b")
                {
                    dataContext.InteractiveShow.LogShow("进入优先模式B" + xmllableCofigs.Xmlpath);
                    //单一数据源优选
                    #region 单一数据源
                    string parentid = "";
                    DataModel dataOpModel = new DataModel();
                    if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2") == null)
                    {
                        string xmlpath = "";
                        for (int i = 0; i < xmllableCofigs.Xmlpath.Split('/').Length - 1; i++)
                        {
                            if (xmlpath == "")
                            {
                                xmlpath = xmllableCofigs.Xmlpath.Split('/')[i];
                            }
                            else
                            {
                                xmlpath = xmlpath + "/" + xmllableCofigs.Xmlpath.Split('/')[i];
                            }
                        }
                        if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmlpath && a.State != "2") != null)
                        {
                            parentid = dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmlpath).ID;
                            dataModelsAissNodeList[0].ParentId = parentid;
                            List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelsAissNodeList[0]);
                            foreach (DataModel aissmodel in dataModelListRestAiss)
                            {
                                aissmodel.State = "1";
                                dataModelsOPList.Add(aissmodel);
                            }
                        }
                    }
                    else
                    {
                        dataOpModel = dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2");
                        string modesours = dataOpModel.sourceData.sourceList.FirstOrDefault(a => a.IsCheck == "1").SourceCode;
                        string soursnameopid = OptimizeElement.Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == modesours.ToLower()).id.ToString();
                        string soursnameasisid = OptimizeElement.Sourcedatadefine[0].SourcedataList.FirstOrDefault(a => a.Code.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()).id.ToString();
                        int opsum = ListByCount(xmllableCofigs.Priority.Split('>').ToList(), soursnameopid);
                        int assum = ListByCount(xmllableCofigs.Priority.Split('>').ToList(), soursnameasisid);
                        if (assum <= opsum)
                        {

                            if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2") != null)
                            {
                                List<DataModel> dataModelListOp = dataModelsOPList.Where(a => a.XmlPath == xmllableCofigs.Xmlpath && a.State != "2").ToList();
                                foreach (DataModel dataop in dataModelListOp)
                                {
                                    List<DataModel> dataModelListRest = SubordinateDataModelList(dataModelsOPList, dataop);
                                    parentid = dataop.ParentId;
                                    foreach (DataModel dataModelOP in dataModelListRest)
                                    {
                                        dataModelOP.State = "2";
                                    }
                                }
                            }

                            foreach (DataModel dataModelAiss in dataModelsAissNodeList)
                            {
                                if (dataModelsOPList.FirstOrDefault(a => a.XmlPath == dataModelAiss.XmlPath && a.State != "2") == null)
                                {
                                    List<DataModel> dataModelListRestAiss = SubordinateDataModelList(dataModelAsisList, dataModelAiss);
                                    dataModelListRestAiss.FirstOrDefault(a => a.ID == dataModelAiss.ID).ParentId = parentid;
                                    dataModelListRestAiss = JsonConvert.DeserializeObject<List<DataModel>>(JsonConvert.SerializeObject(dataModelListRestAiss));
                                    foreach (DataModel aissmodel in dataModelListRestAiss)
                                    {
                                        aissmodel.State = "1";
                                        dataModelsOPList.Add(aissmodel);
                                    }
                                }
                            }
                        }

                    }

                    #endregion
                }
                else
                {
                    #region 多数据源优选
                    foreach (DataModel dataModelAsisNode in dataModelsAissNodeList)
                    {
                        dataContext.InteractiveShow.LogShow("当前分析的路径" + dataModelAsisNode.XmlPath);
                        dataContext.InteractiveShow.LogShow("当前分析的id" + dataModelAsisNode.ID);
                        List<DataModel> dataModelListAsis = new List<DataModel>();//分析下级循环合集
                        List<DataModel> dataModelListOP = new List<DataModel>();//优选下级循环合集
                        dataModelListAsis = dataModelAsisList;
                        dataModelListOP = dataModelsOPList;
                        Xmllable xmllableCofig = XmllableList.FirstOrDefault(a => a.Xmlpath == dataModelAsisNode.XmlPath);
                        if (xmllableCofig != null)
                        {
                            bool determine = true;
                            if (xmllableCofig.ConditionList.Count > 0)
                            {
                                try
                                {
                                    determine = ConditionDetermine(xmllableCofig.ConditionList);
                                }
                                catch (Exception ef)
                                {
                                    dataContext.InteractiveShow.LogShow("当前数据项条件解析错误，配置信息：" + JsonConvert.SerializeObject(ef.ToString()));
                                    dataContext.InteractiveShow.LogShow("当前数据项条件解析错误，错误信息：" + ef.ToString());
                                }
                            }
                            if (determine)
                            {
                                DataModel dataModelOpSging = new DataModel();
                                if (xmllableCofig.Type == "a")
                                {

                                    foreach (var element in xmllableCofig.SignnodeList.NodeList)
                                    {
                                        if (dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == element.Code) != null)
                                        {
                                            string elementvalue = dataModelAsisNode.AttributesList.FirstOrDefault(a => a.Name == element.Code).sourceList.FirstOrDefault(a => a.IsCheck == "1").SaveValue;
                                            dataContext.InteractiveShow.LogShow("进入标识优选值：" + elementvalue);
                                            if (elementvalue != null)
                                            {
                                                dataContext.InteractiveShow.LogShow("标识列不为空：" + elementvalue);
                                                dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == xmllableCofig.Xmlpath && a.AttributesList.FirstOrDefault(b => b.Name == element.Code &&
                                                 b.sourceList.FirstOrDefault(s => s.IsCheck == "1" && s.SaveValue == elementvalue) != null) != null);
                                                if (dataModelOpSging != null)
                                                {
                                                    dataContext.InteractiveShow.LogShow("进入标识查询成功!");
                                                    dataModelListOP = SubordinateDataModelList(dataModelsOPList, dataModelOpSging);
                                                    List<DataModel> parentNodeModel = ParendNodeDataModelList(dataModelsOPList, dataModelOpSging);
                                                    dataModelListOP.AddRange(parentNodeModel);

                                                }
                                            }
                                            else
                                            {
                                                dataContext.InteractiveShow.LogShow("标识列为空：" + elementvalue);

                                            }
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == xmllableCofig.Xmlpath && a.State != "2");
                                }
                                dataContext.InteractiveShow.LogShow(dataContext.DataLayerOpt.MsgId + "旧当前节点：" + JsonConvert.SerializeObject(dataModelAsisNode));

                                dataContext.InteractiveShow.LogShow(dataContext.DataLayerOpt.MsgId + "旧优选结果节点：" + JsonConvert.SerializeObject(dataModelOpSging));
                                OptimizationData(dataModelAsisNode, dataModelOpSging, xmllableCofig, dataModelListOP, dataModelAsisList, OptimizeElement.Sourcedatadefine);
                            }
                            CasecaseuseElmentOptimization(dataModelAsisList, dataModelAsisNode.ID, dataModelListOP, XmllableList);
                            foreach (DataModel opModel in dataModelListOP)
                            {
                                if (dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID && a.State == opModel.State) != null)
                                {

                                    DataModel model = dataModelsOPList.FirstOrDefault(a => a.ID == opModel.ID);
                                    model = opModel;

                                }
                                else
                                {
                                    dataModelsOPList.Add(opModel);
                                }
                            }
                        }
                        else
                        {
                            DataModel dataModelOpSging = dataModelListOP.FirstOrDefault(a => a.XmlPath == dataModelAsisNode.XmlPath && a.State != "2");
                            if (dataModelOpSging == null)
                            {
                                //获取上级节点信息
                                string parentxml = "";
                                List<string> pathlist = dataModelAsisNode.XmlPath.Split('/').ToList();
                                pathlist.RemoveAt(pathlist.Count - 1);
                                parentxml = string.Join("/", pathlist);
                                CaseNodeUpdate(dataModelListOP, parentxml);
                                DataModel nodeParent = dataModelListOP.FirstOrDefault(a => a.XmlPath == parentxml && a.State != "2");
                                if (nodeParent != null)
                                {
                                    string message = JsonConvert.SerializeObject(dataModelAsisNode);
                                    DataModel dataModelAddNode = JsonConvert.DeserializeObject<DataModel>(message);
                                    dataModelAddNode.ParentId = nodeParent.ID;
                                    dataModelListOP.Add(dataModelAddNode);
                                    dataModelsOPList.Add(dataModelAddNode);
                                }

                            }
                            else
                            {
                                List<DataModel> opList = dataModelListOP.Where(a => a.XmlPath == dataModelAsisNode.XmlPath && a.State != "2").ToList();
                                if (opList.Count > 0)
                                {
                                    if (!ISsameNode(opList, dataModelAsisNode))
                                    {
                                        //不存在该节点
                                        string parentxml = "";
                                        List<string> pathlist = dataModelAsisNode.XmlPath.Split('/').ToList();
                                        pathlist.RemoveAt(pathlist.Count - 1);
                                        parentxml = string.Join("/", pathlist);
                                        if (string.IsNullOrEmpty(parentxml))
                                        {
                                            parentxml = dataModelAsisNode.XmlPath;
                                        }
                                        else
                                        {
                                            CaseNodeUpdate(dataModelListOP, parentxml);
                                        }
                                        DataModel nodeParent = dataModelListOP.FirstOrDefault(a => a.XmlPath == parentxml && a.State != "2");
                                        string message = JsonConvert.SerializeObject(dataModelAsisNode);
                                        DataModel dataModelAddNode = JsonConvert.DeserializeObject<DataModel>(message);
                                        dataModelAddNode.ParentId = nodeParent.ID;
                                        dataModelListOP.Add(dataModelAddNode);
                                    }
                                }
                            }
                            CasecaseuseElmentOptimization(dataModelAsisList, dataModelAsisNode.ID, dataModelsOPList, XmllableList);
                        }

                    }
                    #endregion
                }
            }
        }


        /// <summary>
        /// 案件要素嵌套案由要素
        /// </summary>
        /// <param name="caseElmentdataModelList"></param>
        /// <param name="causeElementdataModelList"></param>
        //public void CaseElementListByCauseElmentList(List<DataModel> caseElmentdataModelList, List<DataModel> causeElementdataModelList)
        //{
        //    var locationModel= locationModelList.FirstOrDefault(a => a.DocType.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower());
        //    if (locationModel != null && causeElementdataModelList != null && causeElementdataModelList.Count > 0 && caseElmentdataModelList.Count > 0)
        //    {
        //        string path = locationModel.EelementPaht;
        //        DataModel dataModelCause = caseElmentdataModelList.FirstOrDefault(a => a.XmlPath == path);
        //        if (dataModelCause == null)
        //        {
        //            CaseNodeUpdate(caseElmentdataModelList, path);
        //            dataModelCause = caseElmentdataModelList.FirstOrDefault(a => a.XmlPath == path);
        //        }
        //        if (dataModelCause!=null)
        //        {
        //            DelectNodeByDataModel(dataModelCause.ID, caseElmentdataModelList);
        //        }
        //        DataModel dataRomve = caseElmentdataModelList.FirstOrDefault(a => a.XmlPath == path + "/案由要素");
        //        //删除节点
        //        if (dataRomve != null)
        //        {
        //            caseElmentdataModelList.Remove(dataRomve);
        //        }
        //        //重新复制ID项
        //        RestructureElment(causeElementdataModelList, dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID, dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID);
        //        DataModel dataModelCauseName = new DataModel();
        //        dataModelCauseName.ID = Snowflake.Instance().GetId().ToString();
        //        dataModelCauseName.XmlPath = path + "/案由要素";
        //        dataModelCauseName.sourceData = new SourceData();
        //        dataModelCauseName.CauseType = "1";
        //        dataModelCauseName.ParentId = dataModelCause?.ID;
        //        dataModelCauseName.sourceData.sourceList = new List<Source>();
        //        Source source = new Source();
        //        source.SourceCode = dataContext.DataLayerAns.SourceCode;
        //        source.IsCheck = "1";
        //        dataModelCauseName.sourceData.sourceList.Add(source);
        //        caseElmentdataModelList.Add(dataModelCauseName);
        //        //保存案由要素优选结果
        //        dataContext.DataLayerOpt.ElementOptimizationResults = causeElementdataModelList;
        //        List<DataModel> dataModelCauseModleList = causeElementdataModelList.Where(a => a.ParentId == dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID).ToList();
        //        //案由要素优选结果
        //        DataSoursModel causeDataSoursModel = new DataSoursModel();
        //        causeDataSoursModel.dataModelList = new List<DataModel>();

        //        foreach (DataModel causeModel in dataModelCauseModleList)
        //        {
        //            if (causeElementdataModelList.FirstOrDefault(a => a.ParentId == causeModel.ID && a.XmlPath.IndexOf("主张方") > -1) != null)
        //            {
        //                List<DataModel> dataModelElment = SubordinateDataModelList(causeElementdataModelList, causeModel);
        //                string datamodeljson = JsonConvert.SerializeObject(dataModelElment);
        //                dataModelElment = JsonConvert.DeserializeObject<List<DataModel>>(datamodeljson);
        //                DataModelIDByReset(dataModelElment, "", "");
        //                string jsondata = JsonConvert.SerializeObject(dataModelElment);
        //                causeDataSoursModel.dataModelList.AddRange(JsonConvert.DeserializeObject<List<DataModel>>(jsondata));
        //                causeModel.ParentId = dataModelCauseName.ID;
        //                dataModelElment.FirstOrDefault(a => a.ParentId == dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID).ParentId = dataModelCauseName.ID;
        //                caseElmentdataModelList.AddRange(dataModelElment);
        //            }
        //            else
        //            {
        //                causeModel.ParentId = dataContext.DataLayerAns.ExtractCaseCausesList[0].CC_ID + "_1";
        //            }
        //        }
        //        //将案由实体赋值给结果动态数据中；
        //        dataContext.DataLayerOpt.OptimizeCauseEntityXml = XmlUtility.SerializeToXml<DataSoursModel>(causeDataSoursModel);
        //        dataContext.DataLayerOpt.SourdatModleList = caseElmentdataModelList;
        //        dataContext.DataLayerOpt.OptimizationXml = DataModelByXml(caseElmentdataModelList);
              
        //    }
        //}

        private List<DOCLocationModel> GetLocationModels(string causeLocalXml,string causeStageXml)
        {
            List<CTLocationModel> cTLocations = new List<CTLocationModel>();
            ParseLocationConfig locationConfigM = new ParseLocationConfig();
            var locationModels = locationConfigM.GetLocationModel(causeLocalXml, causeStageXml, dataContext.DataLayerOpt.OptimizationXml, dataContext.DataLayerAns.CaseType, dataContext.DataLayerAns.SourceCode);
            return locationModels;
        }

    }
}
